<template>
  <div class="container">
    <div class="formbox">
      <h3>企业门户网站管理系统</h3>
      <el-form
        ref="loginFormRef"
        style="max-width: 600px"
        :model="loginForm"
        status-icon
        :rules="loginFormRules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(loginFormRef)"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useLoginStore } from '@/stores/index'
const loginStore = useLoginStore()
//定义路由对象
const router = useRouter()
//定义表单ref
const loginFormRef = ref<FormInstance>()
//定义表单数据和校验规则
const loginForm = reactive({
  username: '',
  password: '',
})
const loginFormRules = reactive<FormRules<typeof loginForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  //1、校验表单
  //2、发起登录请求
  //3、保存token到本地存储
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios.post('/adminapi/user/login', loginForm).then((res) => {
        if (res.data.code === '0') {
          console.log(res.data.data)
          //保存用户信息
          loginStore.setUserInfo(res.data.data)
          //跳转到首页
          router.push('/index')
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    } else {
      console.log('error submit!!')
    }
  })
}
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: rgb(51.2, 126.4, 204);
  .formbox {
    width: 300px;
    padding: 20px;
    border-radius: 10px;
    background-color: rgb(121.3, 187.1, 255);
    text-align: center;
    h3 {
      padding-bottom: 20px;
    }
  }
}
::v-deep(.el-form-item__label) {
  color: #fff;
}
::v-deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>
